// Definition for a binary tree node.
function TreeNode(val, left, right) {
  this.val = (val === undefined ? 0 : val)
  this.left = (left === undefined ? null : left)
  this.right = (right === undefined ? null : right)
}

function createTree(arr) {
  if (arr.length < 1)
    return null;
  let NodeArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] == null) {
      NodeArr.push(null);
      continue;
    }
    let tempNode = new TreeNode(arr[i], null, null);
    NodeArr.push(tempNode);
  }
  for (let i = 0; i < arr.length; i++) {
    if (NodeArr[i] == null) continue;
    if (2 * i + 1 < arr.length)
      NodeArr[i].left = NodeArr[2 * i + 1];
    if (2 * i + 2 < arr.length)
      NodeArr[i].right = NodeArr[2 * i + 2];
  }
  return NodeArr[0];
}

function preShow(node) {
  if (node == null)
    return;
  console.log(node.val);
  preShow(node.left);
  preShow(node.right);
}
/**
 * @param {number[]} preorder
 * @param {number[]} inorder
 * @return {TreeNode}
 */
var buildTree = function (preorder, inorder) {
  // 如果长度为0，返回null
  if (!preorder.length) return null;
  // 取值
  const val = preorder[0];
  // 获得根节点
  const root = new TreeNode(val);
  // 找到中序的位置
  const index = inorder.indexOf(val);
  // 左边开始遍历
  root.left = buildTree(preorder.slice(1, index + 1), inorder.slice(0, index));
  // 右边开始遍历
  root.right = buildTree(preorder.slice(index + 1), inorder.slice(index + 1));
  return root;
};
let preorder = [3,9,20,15,7], inorder = [9,3,15,20,7];
console.log(buildTree(preorder, inorder));
preorder = [-1], inorder = [-1];
console.log(buildTree(preorder, inorder));
